import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const rememberPassword = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userRole = computed(() => userInfo.value.roleName || '')
  const isMinister = computed(() => userRole.value === '部长')
  const isProjectLeader = computed(() => userRole.value === '项目负责人')
  const isFrontendLeader = computed(() => userRole.value === '前端负责人')
  const isBackendLeader = computed(() => userRole.value === '后端负责人')
  const isDeveloper = computed(() => userRole.value === '成员（开发者）')

  // 方法
  const login = async (credentials) => {
    try {
      const response = await loginApi(credentials)
      const { token: newToken, user } = response.data
      
      token.value = newToken
      userInfo.value = user
      
      // 保存到本地存储
      localStorage.setItem('token', newToken)
      localStorage.setItem('userInfo', JSON.stringify(user))
      
      // 记住密码功能
      if (rememberPassword.value) {
        localStorage.setItem('rememberedUsername', credentials.username)
        localStorage.setItem('rememberedPassword', credentials.password)
      } else {
        localStorage.removeItem('rememberedUsername')
        localStorage.removeItem('rememberedPassword')
      }
      
      return { success: true }
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.message || '登录失败，请重试' 
      }
    }
  }

  const logout = () => {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  const checkRememberedCredentials = () => {
    const rememberedUsername = localStorage.getItem('rememberedUsername')
    const rememberedPassword = localStorage.getItem('rememberedPassword')
    
    if (rememberedUsername && rememberedPassword) {
      rememberPassword.value = true
      return { username: rememberedUsername, password: rememberedPassword }
    }
    
    return null
  }

  const hasPermission = (permission) => {
    // 部长拥有所有权限
    if (isMinister.value) return true
    
    // 根据角色判断权限
    switch (permission) {
      case 'view_all_projects':
        return isMinister.value || isProjectLeader.value
      case 'edit_project':
        return isMinister.value || isProjectLeader.value
      case 'manage_members':
        return isMinister.value || isProjectLeader.value
      case 'view_documents':
        return true // 所有角色都可以查看文档
      case 'upload_documents':
        return isMinister.value || isProjectLeader.value || isFrontendLeader.value || isBackendLeader.value
      default:
        return false
    }
  }

  return {
    // 状态
    token,
    userInfo,
    rememberPassword,
    
    // 计算属性
    isLoggedIn,
    userRole,
    isMinister,
    isProjectLeader,
    isFrontendLeader,
    isBackendLeader,
    isDeveloper,
    
    // 方法
    login,
    logout,
    checkRememberedCredentials,
    hasPermission
  }
})
